﻿#region Copyright (c) 2013-04, Olaf Kober <amarok.projects@gmail.com>
//================================================================================
//	Permission is hereby granted, free of charge, to any person obtaining a copy
//	of this software and associated documentation files (the "Software"), to deal
//	in the Software without restriction, including without limitation the rights
//	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//	copies of the Software, and to permit persons to whom the Software is
//	furnished to do so, subject to the following conditions:
//
//	The above copyright notice and this permission notice shall be included in
//	all copies or substantial portions of the Software.
//
//	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//	THE SOFTWARE.
//================================================================================
#endregion

using System;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Tasks.Dataflow;


namespace Amarok.Agents
{
	/// <summary>
	/// </summary>
	internal abstract class SubscriptionBase : CompletableObject
	{
		// data
		private readonly CancellationTokenSource mCancellationTokenSource = new CancellationTokenSource();
		private readonly Type mMessageType;
		private readonly ActionBlock<Message> mActionBlock;
		private Predicate<Message> mMessageFilter;
		private Action<SubscriptionBase> mRemoveSubscriptionAction;
		private IDisposable mActionBlockDisposable;

		// state
		private Boolean mIsFirstMessage = true;


		#region ++ Public Interface ++

		/// <summary>
		/// </summary>
		public void Link(BroadcastBlock<Message> broadcastBlock)
		{
			Verify.NotNull(broadcastBlock, "broadcastBlock");
			mActionBlockDisposable = _Link(broadcastBlock);
		}

		#endregion

		#region ## Protected Interface ##

		/// <summary>
		/// </summary>
		protected SubscriptionBase(Type messageType, Predicate<Message> messageFilter,
			Action<SubscriptionBase> removeSubscriptionAction)
		{
			Verify.IsAssignableTo(messageType, typeof(Message), "messageType");
			Verify.NotNull(removeSubscriptionAction, "removeSubscriptionAction");

			mMessageType = messageType;
			mMessageFilter = messageFilter;
			mRemoveSubscriptionAction = removeSubscriptionAction;
			mActionBlock = _CreateActionBlock(this.Post);
		}

		#endregion

		#region ## Overridable Methods ##

		/// <summary>
		/// </summary>
		protected abstract void Post(Message message);

		#endregion

		#region Implementation

		protected override Task OnComplete(Boolean discardAvailableMessages)
		{
			var completionSource = new TaskCompletionSource();

			// unlink from broadcast block
			if (mActionBlockDisposable != null)
				mActionBlockDisposable.Dispose();

			// cancel pending messages
			if (discardAvailableMessages)
				mCancellationTokenSource.Cancel();

			// complete action block
			mActionBlock.Complete();
			mActionBlock.Completion.ContinueWith(t1 =>
				{
					// clean up
					_RemoveSubscription();

					// done
					completionSource.SignalCompletion();
				},
				TaskContinuationOptions.ExecuteSynchronously);

			return completionSource.Task;
		}

		protected override void OnCompleted()
		{
			mCancellationTokenSource.Dispose();

			mMessageFilter = null;
			mRemoveSubscriptionAction = null;
		}

		private void _RemoveSubscription()
		{
			var action = mRemoveSubscriptionAction;

			if (action != null)
				action(this);
		}

		private ActionBlock<Message> _CreateActionBlock(Action<Message> handler)
		{
			var options = new ExecutionDataflowBlockOptions()
			{
				BoundedCapacity = AgentGlobals.BoundedCapacity,
				MaxMessagesPerTask = AgentGlobals.MaxMessagesPerTask,
				MaxDegreeOfParallelism = 1,
				NameFormat = "Publisher-ActionBlock: Id: {1}",
				CancellationToken = mCancellationTokenSource.Token,
				TaskScheduler = TaskScheduler.Default,
			};

			return new ActionBlock<Message>(handler, options);
		}

		private IDisposable _Link(BroadcastBlock<Message> broadcastBlock)
		{
			var options = new DataflowLinkOptions()
			{
				Append = true,
				PropagateCompletion = false,
			};

			return broadcastBlock.LinkTo(
				mActionBlock,
				options,
				_Filter);
		}

		private Boolean _Filter(Message message)
		{
			if (mIsFirstMessage)
			{
				mIsFirstMessage = false;
				return false;
			}

			if (mMessageType.IsInstanceOfType(message) == false)
				return false;

			if (mMessageFilter == null)
				return true;

			return mMessageFilter(message);
		}

		#endregion

	}
}
